import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';
import { FriendStatus } from '@/app/types/friend';

export async function POST(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { requestId } = await req.json();

    if (!requestId) {
      return NextResponse.json({ error: '缺少请求ID' }, { status: 400 });
    }

    const friendRequest = await prisma.friend.findUnique({
      where: { id: requestId },
    });

    if (!friendRequest) {
      return NextResponse.json({ error: '好友请求不存在' }, { status: 404 });
    }

    // 验证当前用户是否是该请求的接收者
    if (friendRequest.friendId !== userId) {
      return NextResponse.json({ error: '无权操作该好友请求' }, { status: 403 });
    }

    if (friendRequest.status !== FriendStatus.PENDING) {
      return NextResponse.json({ error: '该请求已被处理' }, { status: 400 });
    }

    // 直接删除请求记录
    await prisma.friend.delete({
      where: { id: requestId },
    });

    return NextResponse.json({ message: '已拒绝好友请求' }, { status: 200 });
  } catch (error: any) {
    console.error('拒绝好友请求失败:', error);
    return NextResponse.json({ error: '服务器内部错误' }, { status: 500 });
  }
} 